package com.yiya.service;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yiya.bean.OrderDetail;
import com.yiya.bean.OrderInfo;
import com.yiya.bean.SysUser;
import com.yiya.mapper.OrderDetailMapper;
import com.yiya.mapper.OrderInfoMapper;
import com.yiya.model.OrderInfoCplex;
import com.yiya.model.OrderInfoCplexModel;

@Service("orderInfoService")
public class OrderInfoService {
	@SuppressWarnings("unused")
	private final static Logger log = Logger.getLogger(OrderInfoService.class);

	@Autowired
	private OrderInfoMapper orderInfoMapper;
	
	@Autowired
	private OrderDetailMapper orderDetailMapper;
	
	public List<OrderInfoCplex> queryByList(OrderInfoCplexModel bean) {
		Integer rowCount = queryByCount(bean);
		bean.getPager().setRowCount(rowCount);
		List<OrderInfoCplex> list = orderInfoMapper.selectByModel(bean);
		return list;
	}
	
	public int queryByCount(OrderInfoCplexModel bean){
		return orderInfoMapper.countByModel(bean);
	}
	
	public void add(OrderInfo bean){
		orderInfoMapper.insert(bean);
		saveOrderDetails(bean.getId(), bean.getOrderDetails());
	}
	
	public int Update(OrderInfo bean){
		saveOrderDetails(bean.getId(), bean.getOrderDetails());
		return orderInfoMapper.updateByPrimaryKeySelective(bean);
	}
	
	public OrderInfo queryById(Integer id){
		return orderInfoMapper.selectByPrimaryKey(id);
	}
	
	public void delete(Integer[] ids,SysUser user){
		Date nowTime = new Date();
		for(Integer id:ids){
			OrderInfo bean = orderInfoMapper.selectByPrimaryKey(id);
			bean.setUpdateBy(user.getId());
			bean.setUpdateTime(nowTime);
			bean.setDelFlag(1);
			orderInfoMapper.updateByPrimaryKeySelective(bean);
		}
	}
	
	/**
	 * 保存订单子项
	 * @param orderInfoId
	 * @param orderDetails
	 */
	public void saveOrderDetails(Integer orderInfoId,List<OrderDetail> orderDetails){
		if(orderDetails == null||orderDetails.isEmpty()){
			return;
		}
		for(OrderDetail orderDetail:orderDetails){
			if(orderDetail.getId()!= null && "1".equals(orderDetail.getDelFlag())){
				orderDetailMapper.deleteByPrimaryKey(orderDetail.getId());
				continue;
			}
			orderDetail.setOrderId(orderInfoId);
			if(orderDetail.getId() == null){
				orderDetailMapper.insert(orderDetail);
			}else{
				orderDetailMapper.updateByPrimaryKeySelective(orderDetail);
			}
		}
	}
	
	public List<OrderDetail> queryByOrderId(Integer orderId){
		return orderDetailMapper.queryByOrderId(orderId);
	}
	
	public List<OrderInfoCplex> queryAllByList(OrderInfoCplexModel bean) {
		List<OrderInfoCplex> list = orderInfoMapper.selectAllByModel(bean);
		return list;
	}
}
